package comm

import (
	"database/sql/driver"
	"errors"
	"strconv"
	"time"
)

// Timestamp 时间戳类型
type Timestamp time.Time

// UnmarshalJSON 自定义json解析方法
func (m *Timestamp) UnmarshalJSON(p []byte) error {
	ts, err := strconv.ParseInt(string(p), 10, 64)
	if err != nil {
		return err
	}
	*m = Timestamp(time.Unix(0, ts*int64(time.Millisecond)))
	return nil
}

// Value - Implementation of valuer for database/sql
func (m Timestamp) Value() (driver.Value, error) {
	return time.Time(m), nil
}

// Scan - Implement the database/sql scanner interface
func (m *Timestamp) Scan(src interface{}) error {
	if src == nil {
		*m = Timestamp(DefaultDateTime)
		return nil
	}
	switch src.(type) {
	case time.Time:
		*m = Timestamp(src.(time.Time))
		return nil
	default:
		return errors.New("无法解析的日期类型")
	}
}

// DefaultDateTime 默认时间，1970-01-01
var DefaultDateTime, _ = time.ParseInLocation("2006-01-02 15:04:05", "1970-01-01 00:00:00", time.Local)

// DefaultDateTimePattern 默认格式
const DefaultDateTimePattern = "2006-01-02 15:04:05"

// SlashDateTimePattern 斜线格式
const SlashDateTimePattern = "2006/01/02 15:04:05"

// CompactDateTimePattern 紧凑格式
const CompactDateTimePattern = "20060102 15:04:05"

// DefaultDatePattern 默认格式
const DefaultDatePattern = "2006-01-02"

// CompactDatePattern 紧凑格式
const CompactDatePattern = "20060102"

// ParseTime 解析日期时间
func ParseTime(date, format string) (time.Time, error) {
	d, err := time.ParseInLocation(format, date, time.Local)
	if err != nil {
		return DefaultDateTime, err
	}
	return d, nil
}

// MustParseTime 解析日期时间，支持yyyy-MM-dd HH:mm:ss和yyyy/MM/dd HH:mm:ss两种格式
// 空字符串或解析出错时返回 DefaultDate。
func MustParseTime(date, format string) time.Time {
	t, _ := ParseTime(date, format)
	return t
}
